let covers = [];
let tags = [];
let selectedImageData = null;
let search_image_to_field = ""
const tagsContainer = document.getElementById('tagsContainer');
const hiddenTagsField = document.getElementById('tags');
const dyTags = document.getElementById('dy_tags');
const addImageModal = document.getElementById('addImageModal');
const search_image_key = document.getElementById('search_image_key');
const imageGrid = document.getElementById('imageGrid');
const CoversContainer = document.getElementById('CoversContainer');
const hiddenCoversField = document.getElementById('covers');
const hiddenCostDistributionField = document.getElementById('cost_distribution_uri');
const costDistributionContainer = document.getElementById('CostDistributionContainer');
const hiddenAssuranceField = document.getElementById('assurance_uri');
const assuranceContainer = document.getElementById('AssuranceContainer');
const qualification = document.getElementById('qualification');
const formRecord = document.getElementById('form_record');

function changeQualification() {
    if (qualification.getAttribute('record_key') === qualification.value) {
        formRecord.classList.remove('hidden');
    } else {
        formRecord.classList.add('hidden');
    }
}

function showAddModal(to_field) {
    search_image_to_field = to_field
    search_image_key.value = "";
    imageGrid.innerHTML = "";
    addImageModal.classList.remove('hidden');
    addImageModal.classList.add('flex');
}

function hideAddModal() {
    selectedImageData = null;
    search_image_to_field = ""
    addImageModal.classList.remove('flex');
    addImageModal.classList.add('hidden');
}

function toggleCheckbox(checkbox) {
    const icon = checkbox.querySelector('i');
    checkbox.classList.toggle('checked');
    icon.classList.toggle('hidden');
}

function radioSelectImage(radiobox) {
    selectedImageData = JSON.parse(radiobox.getAttribute('image_data'));

    // 更新所有单选按钮状态
    document.querySelectorAll('.custom-radio').forEach(radio => {
        var imageJson = JSON.parse(radio.getAttribute('image_data'));
        radio.classList.toggle('checked', selectedImageData.id === imageJson.id);
    });
}

function searchImage() {
    imageGrid.innerHTML = "";
    selectedImageData = null;
    axios.get("/image_library/list/" + search_image_key.value, {}, {
        headers: {
            'X-CSRFToken': document.getElementById('csrf_token').value,
            'Content-Type': 'application/json'
        }
    }).then(response => {
        if (response.data.data.length !== 0) {
            imageGrid.classList.add('grid');
            response.data.data.forEach(img => {
                addSearchImage(imageGrid, img)
            });
        } else {
            imageGrid.classList.remove('grid');
            imageGrid.innerHTML = "暂无数据";
        }

    })
}

function addSearchImage(imageGrid, imageJson) {
    const check_data = JSON.stringify({id: imageJson.id, title: imageJson.title, file_url: imageJson.file_url})
    const tagElement = document.createElement('div');
    tagElement.className = 'image-container';
    if (search_image_to_field === "covers") {
        tagElement.innerHTML = `<div class="checkbox-wrapper">
                                <div class="custom-checkbox " onclick="toggleCheckbox(this)" image_data='${check_data}'>
                                    <i class="fas fa-check hidden"></i></div></div>`;
    } else {
        tagElement.innerHTML = `<div class="radio-container">
                                <div class="custom-radio " onclick="radioSelectImage(this)" image_data='${check_data}'>
                                <i class="fas fa-check hidden"></i></div></div>`;
    }

    tagElement.innerHTML += `<div class="image-wrapper"><img src="${imageJson.file_url}" alt="${imageJson.title}"></div>`;
    imageGrid.appendChild(tagElement);
}


function addImage() {
    if (search_image_to_field === "covers") {
        var elements = document.querySelectorAll('.custom-checkbox.checked');
        elements.forEach(function (element) {
            var imageJson = JSON.parse(element.getAttribute('image_data'));
            covers.push(imageJson);
        });

        updateCoversDisplay();
        updateHiddenCoverField();
    } else if (search_image_to_field === "cost_distribution_uri") {
        updateCostDistributionDisplay();
        updateHiddenCostDistributionField();

    } else if (search_image_to_field === "assurance_uri") {
        updateAssuranceDisplay();
        updateHiddenAssuranceField();
    }

    hideAddModal();
}

function updateCostDistributionDisplay(is_close = true) {
    costDistributionContainer.innerHTML = '';
    if (selectedImageData !== null && selectedImageData !== "") {
        const tagElement = document.createElement('div');
        tagElement.className = 'relative';
        tagElement.innerHTML = `<img src="${selectedImageData.file_url}" class="max-w-270 max-h-270 object-cover" alt="${selectedImageData.title}" />`;
        if (is_close) {
            tagElement.innerHTML += `<button type="button" class="btn-close absolute end-0 top-0 bg-white" onclick="clearContainer('${search_image_to_field}')"></button>`;
        }
        costDistributionContainer.appendChild(tagElement);
    }
}

function updateHiddenCostDistributionField() {
    hiddenCostDistributionField.value = JSON.stringify(selectedImageData);
}

function updateAssuranceDisplay(is_close = true) {
    assuranceContainer.innerHTML = '';
    if (selectedImageData !== null && selectedImageData !== "") {
        const tagElement = document.createElement('div');
        tagElement.className = 'relative';
        tagElement.innerHTML = `<img src="${selectedImageData.file_url}" class="max-w-270 max-h-270 object-cover" alt="${selectedImageData.title}" />`;
        if (is_close) {
            tagElement.innerHTML += `<button type="button" class="btn-close absolute end-0 top-0 bg-white" onclick="clearContainer('${search_image_to_field}')"></button>`;
        }
        assuranceContainer.appendChild(tagElement);
    }
}

function updateHiddenAssuranceField() {
    hiddenAssuranceField.value = JSON.stringify(selectedImageData);
}

function clearContainer(containerText) {
    if (containerText === "cost_distribution_uri") {
        costDistributionContainer.innerHTML = '';
        hiddenCoversField.value = '';
    } else if (containerText === "assurance_uri") {
        assuranceContainer.innerHTML = '';
        hiddenAssuranceField.value = '';
    }
}

function updateHiddenCoverField() {
    console.log(JSON.stringify(covers))
    hiddenCoversField.value = JSON.stringify(covers);
}

function updateCoversDisplay(is_close = true) {
    CoversContainer.innerHTML = '';
    covers.forEach(cover => {
        const tagElement = document.createElement('div');
        tagElement.className = 'relative';
        tagElement.innerHTML = `<img src="${cover.file_url}" class="max-w-270 max-h-270 object-cover" alt="${cover.title}" />`;
        if (is_close) {
            tagElement.innerHTML += `<button type="button" class="btn-close absolute end-0 top-0 bg-white" onclick="removeCover(${cover.id})"></button>`;
        }

        CoversContainer.appendChild(tagElement);
    });
}

function removeCover(coverToRemove) {
    covers = covers.filter(cover => cover.id !== coverToRemove);
    updateCoversDisplay();
    updateHiddenCoverField();
}


function addDisplayTag(tagsContainer, tagJson, is_close = true) {
    const tagElement = document.createElement('div');
    if (is_close) {
        tagElement.className = 'flex gap-2 ps-3 pe-2 py-1 rounded-full text-sm border';
    } else {
        tagElement.className = 'flex gap-2 ps-3 pe-3 py-1 rounded-full text-sm border';
    }

    tagElement.innerHTML = tagJson.name;
    if (is_close) {
        tagElement.innerHTML += `<button type="button" onclick="removeTag('${tagJson.id}')"><i class="fas fa-times text-xs"></i></button>`;
    }
    tagsContainer.appendChild(tagElement);
}

// 添加标签函数
function addTag() {
    const tagValue = dyTags.value.trim();
    const tagText = dyTags.options[dyTags.selectedIndex].text;
    if (tagValue && !tags.some(item => item.id === tagValue) && tags.length < 3) {
        tagJson = {id: tagValue, name: tagText}
        tags.push(tagJson);
        updateTagsDisplay();
        updateHiddenTagField();
        dyTags.selectedIndex = 0;
    }
}

// 删除标签函数
function removeTag(tagToRemove) {
    tags = tags.filter(tag => tag.id !== tagToRemove);
    updateTagsDisplay();
    updateHiddenTagField();
}

// 更新标签显示
function updateTagsDisplay(is_close = true) {
    tagsContainer.innerHTML = '';
    tags.forEach(tag => {
        addDisplayTag(tagsContainer, tag, is_close)
    });
}

function updateHiddenTagField() {
    hiddenTagsField.value = JSON.stringify(tags);
}

function initContainer(is_close = true) {
    if (hiddenTagsField.value !== JSON.stringify(tags)) {
        tags = JSON.parse(hiddenTagsField.value);
    }
    updateTagsDisplay(is_close);

    if (hiddenCoversField.value !== JSON.stringify(covers)) {
        covers = JSON.parse(hiddenCoversField.value);
    }
    updateCoversDisplay(is_close);

    if (hiddenCostDistributionField.value.length > 0) {
        selectedImageData = JSON.parse(hiddenCostDistributionField.value);
    }
    updateCostDistributionDisplay(is_close);
    selectedImageData = null;

    if (hiddenAssuranceField.value.length > 0) {
        selectedImageData = JSON.parse(hiddenAssuranceField.value);
    }
    updateAssuranceDisplay(is_close);
    selectedImageData = null;
}

